package com.scut.edu.wanyou.home.talk;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Collection;

import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smackx.packet.VCard;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.scut.edu.wanyou.home.ChildHolder;

public class Friends {
	private  Connection connection;
	private Roster roster;
	public Friends()
	{
		connection = XmppTool.getConnection();
		
	}
	/**
	 * Description:通过id号添加好友;
	 * Date:2013-1-6
	 * @author chenxiaochen * @param userId
	 * @author chenxiaochen * @return 
	 * @return boolean
	 */
	public  boolean addFriendById(String userId)
	{
		roster = connection.getRoster();  
		//发送添加好友请求，并将该jid用户加入到自己的roster中
		try {
			roster.createEntry(userId, userId, new String[]{"Firends"});
			return true;
		} catch (XMPPException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
	public  ArrayList<ChildHolder> getFriends()
	{
		ArrayList<ChildHolder> friends = new ArrayList<ChildHolder>();
		roster= connection.getRoster();
		Collection<RosterEntry> entries = roster.getEntries();
		for (RosterEntry entry : entries) {
			ChildHolder childHolder = new ChildHolder(entry);
            childHolder.userHead = getUserImage(entry.getUser());
            childHolder.stuts = getStatus(entry.getUser());
			friends.add(childHolder);
            Log.i("wanyou msgNumUnRead",""+childHolder.msgNumUnRead);
		}
		return friends;
	}
	public String getStatus(String user)
	{
		Presence presence = roster.getPresence(user);
		return presence.getStatus();
	}
	
	public  Bitmap getUserImage(String user) {  
		Bitmap bitmap=null;
        try {  
            System.out.println("获取用户头像信息: "+user);  
            VCard vcard = new VCard();  
            vcard.load(connection, user);  
              
            if(vcard == null || vcard.getAvatar() == null)  
            {  
            	Log.i("friends","null");
                return null;  
            }  
            //ByteArrayInputStream bais = new ByteArrayInputStream( vcard.getAvatar());  
           Log.i("friends",""+vcard.getAvatar().length);
            bitmap = BitmapFactory.decodeByteArray(vcard.getAvatar(), 0,vcard.getAvatar().length);
            //bitmap = BitmapFactory.decodeStream(bais);
      
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return bitmap;  
	}
}
